/*******************************************************************************
  * 文件：UartComm_Device.c
  * 作者：zyz
  * 版本：v1.0.0
  * 日期：2017-08-03
  * 说明：设备
*******************************************************************************/
/* 头文件 *********************************************************************/
#include "UartComm_Device.h"
#include "UartComm_Dba.h"
#include "UartComm.h"
#include "SensorCtrl.h"
#include "OxygenSensor.h"
#include "RelayCtrl.h"
#include "RelayPower.h"
#include "Hardware_IO.h"
#include "MotorCtrl.h"
#include "InverterCtrl.h"
#include "ZCD.h"

/* 宏定义 *********************************************************************/
/* 类型定义 *******************************************************************/
/* 变量定义 *******************************************************************/
// 数据定义
static LoadReadOnlyData_ts sLoadReadOnlyState;        // 负载只读状态
static LoadReadWriteData_ts sLoadReadWriteState;      // 负载读写状态
static LoadReadWriteData_ts sLoadReadWriteControl;    // 负载读写控制
static LoadWriteOnlyData_ts sLoadWriteOnlyControl;    // 负载只写控制

// 设备状态数据块信息
static UartCommDataBlockInfo_ts asDeviceStateDataBlockInfo[] =
{
    // 负载只读状态
    { u16LOAD_RO_DATA_ADDR, (U8*)&sLoadReadOnlyState,  sizeof(sLoadReadOnlyState)  },
    // 负载读写状态
    { u16LOAD_RW_DATA_ADDR, (U8*)&sLoadReadWriteState, sizeof(sLoadReadWriteState) },
};

// 设备控制数据块信息
static UartCommDataBlockInfo_ts asDeviceControlDataBlockInfo[] =
{
    // 负载读写控制
    { u16LOAD_RW_DATA_ADDR, (U8*)&sLoadReadWriteControl, sizeof(sLoadReadWriteControl) },

    // 负载只写控制
    { u16LOAD_WO_DATA_ADDR, (U8*)&sLoadWriteOnlyControl, sizeof(sLoadWriteOnlyControl) },
};

/* 函数声明 *******************************************************************/
/* 函数定义 *******************************************************************/
/*******************************************************************************
  * 函数名: UartComm_InitDevice
  * 功  能：初始化设备
  * 参  数：无
  * 返回值：无
  * 说  明：无
*******************************************************************************/
void UartComm_InitDevice(void)
{
    // 清零数据
    memset(&sLoadReadOnlyState, 0, sizeof(sLoadReadOnlyState));
    memset(&sLoadReadWriteState, 0, sizeof(sLoadReadWriteState));
    memset(&sLoadReadWriteControl, 0, sizeof(sLoadReadWriteControl));
    memset(&sLoadWriteOnlyControl, 0, sizeof(sLoadWriteOnlyControl));
}

/*******************************************************************************
  * 函数名: UartComm_GetDeviceStateDbaInfo
  * 功  能：获取设备状态DBA信息
  * 参  数：无
  * 返回值：DBA信息
  * 说  明：无
*******************************************************************************/
UartCommDbaInfo_ts UartComm_GetDeviceStateDbaInfo(void)
{
    static const UartCommDbaInfo_ts sDbaInfo =
    {
        asDeviceStateDataBlockInfo,
        ARRAY_SIZE(asDeviceStateDataBlockInfo)
    };

    // 返回DBA信息
    return sDbaInfo;
}

/*******************************************************************************
  * 函数名: UartComm_GetDeviceControlDbaInfo
  * 功  能：获取设备控制DBA信息
  * 参  数：无
  * 返回值：DBA信息
  * 说  明：无
*******************************************************************************/
UartCommDbaInfo_ts UartComm_GetDeviceControlDbaInfo(void)
{
    static const UartCommDbaInfo_ts sDbaInfo =
    {
        asDeviceControlDataBlockInfo,
        ARRAY_SIZE(asDeviceControlDataBlockInfo)
    };

    // 返回DBA信息
    return sDbaInfo;
}

/*******************************************************************************
  * 函数名：UartComm_UpdateLoadState
  * 功  能：更新负载状态
  * 参  数：无
  * 返回值：无
  * 说  明：负载状态包括：只读状态（传感器和限位开关）、读写状态（继电器开关状态）
*******************************************************************************/
void UartComm_UpdateLoadState(void)
{
    LittleEndianU16_tu uTemp;

/* <------------------------------- 负载只读状态 ---------------------------> */
    // byte 0x00-0x01
    uTemp.u16Word = Sensor_GetCavitySensorVal();                                        // 腔体主传感器温度
    sLoadReadOnlyState.sCavityPrimarySensor.u2State = Sensor_GetCavitySensorErr();      // 腔体主传感器状态
    sLoadReadOnlyState.sCavityPrimarySensor.u6ValueMsb = uTemp.sByte.u8Msb;
    sLoadReadOnlyState.sCavityPrimarySensor.u8ValueLsb = uTemp.sByte.u8Lsb;
    // byte 0x02-0x03
    uTemp.u16Word = 0;                                                                  // 腔体副传感器温度
    sLoadReadOnlyState.sCavitySecondarySensor.u2State = 0;                              // 腔体副传感器状态
    sLoadReadOnlyState.sCavitySecondarySensor.u6ValueMsb = uTemp.sByte.u8Msb;
    sLoadReadOnlyState.sCavitySecondarySensor.u8ValueLsb = uTemp.sByte.u8Lsb;
    // byte 0x04-0x05
    uTemp.u16Word = Sensor_GetSteamGeneratorSensorVal();                                // 蒸发器传感器温度
    sLoadReadOnlyState.sSteamerSensor.u2State = Sensor_GetSteamGeneratorSensorErr();    // 蒸发器传感器状态
    sLoadReadOnlyState.sSteamerSensor.u6ValueMsb = uTemp.sByte.u8Msb;
    sLoadReadOnlyState.sSteamerSensor.u8ValueLsb = uTemp.sByte.u8Lsb;
    // byte 0x06-0x07
    uTemp.u16Word = Sensor_GetBottomSensorVal();                                        // 底部传感器温度
    sLoadReadOnlyState.sBottomSensor.u2State = Sensor_GetBottomSensorErr();             // 底部传感器状态
    sLoadReadOnlyState.sBottomSensor.u6ValueMsb = uTemp.sByte.u8Msb;
    sLoadReadOnlyState.sBottomSensor.u8ValueLsb = uTemp.sByte.u8Lsb;
    // byte 0x08-0x09
    uTemp.u16Word = Sensor_GetProbeSensorVal();                                         // 肉感探针传感器温度
    sLoadReadOnlyState.sMeatProbeSensor.u2State = Sensor_GetProbeSensorErr();           // 肉感探针传感器状态
    sLoadReadOnlyState.sMeatProbeSensor.u6ValueMsb = uTemp.sByte.u8Msb;
    sLoadReadOnlyState.sMeatProbeSensor.u8ValueLsb = uTemp.sByte.u8Lsb;
    // byte 0x0A-0x0B
    uTemp.u16Word = Sensor_GetOxygenSensorVal();                                        // 氧传感器浓度
    if(TRUE == OxygenSensorIsWork())
    {
        sLoadReadOnlyState.sOxygenSensor.u2State = 0;                                   // 氧传感器状态
    }
    else
    {
        sLoadReadOnlyState.sOxygenSensor.u2State = 1;                                   // 氧传感器状态
    }
    sLoadReadOnlyState.sOxygenSensor.u6ValueMsb = uTemp.sByte.u8Msb;
    sLoadReadOnlyState.sOxygenSensor.u8ValueLsb = uTemp.sByte.u8Lsb;
    // byte 0x0C
    sLoadReadOnlyState.u1DoorOpenCloseState      = Hardware_DoorStateCheck();           // 门开关状态
    sLoadReadOnlyState.u1SteamerFullState        = Hardware_SteamWaterPosCheck();       // 蒸发器满状态
    sLoadReadOnlyState.u1RestWaterBoxFullState   = Hardware_LeftWaterPosCheck();        // 余水盒满状态
    sLoadReadOnlyState.u1WasteWaterBoxFullState  = Hardware_WasteWaterFullCheck();      // 废水盒满状态
    sLoadReadOnlyState.u1WasteWaterBoxExistState = Hardware_WasteWaterBoxCheck();       // 废水盒在位状态
    // byte 0x0D
    sLoadReadOnlyState.u1ClockSecondFlag         = GetSecondFlag();                     // 时钟秒标志
    sLoadReadOnlyState.u1LoadBoardCommRecvError  = UartComm_GetCommErrorState();        // 负载板通信接收故障状态
    sLoadReadOnlyState.u3LifitingPanelState      = Motor_GetState()-1;                  // 升降面板状态更新

    // byte 0x0E-0x0F  电源板温度传感器数据暂时不用
    
    // byte 0x10
    sLoadReadOnlyState.u8InverterError          = Inverter_GetError();                  // 变频板故障
    
/* <------------------------------- 负载读写状态 ---------------------------> */
    // byte 0x00
    sLoadReadWriteState.u1NeutralWireMasterControl3 = OFF;                              // 零线总控3
    sLoadReadWriteState.u1NeutralWireMasterControl2 = RelayGetZeroLine2State();         // 零线总控2
    sLoadReadWriteState.u1NeutralWireMasterControl1 = RelayGetZeroLine1State();         // 零线总控1
    // byte 0x01
    sLoadReadWriteState.u1MicrowaveMagnetron        = OFF;    // 微波磁控管
    sLoadReadWriteState.u1SteamerInsideHeater       = RelayGetSteamPanInState();        // 蒸发器/盘内管
    sLoadReadWriteState.u1SteamerOutsideHeater      = RelayGetSteamPanOutState();       // 蒸发器/盘外管
    sLoadReadWriteState.u1BackHeater                = RelayGetBackHeatTubeState();      // 背部加热管
    sLoadReadWriteState.u1BottomHeater              = RelayGetDownHeatTubeState();      // 底部加热管
    sLoadReadWriteState.u1TopInsideHeater           = RelayGetUpInHeatTubeState();      // 上内加热管
    sLoadReadWriteState.u1TopOutsideHeater          = RelayGetUpOutHeatTubeState();     // 上外加热管
    // byte 0x02
    sLoadReadWriteState.u1MicrowaveTurntableMotor   = OFF;    // 微波转盘电机
    sLoadReadWriteState.u1MicrowaveCoolingFan       = OFF;    // 微波散热风机
    sLoadReadWriteState.u1RoastingForkMotor         = OFF;    // 烤叉电机
    sLoadReadWriteState.u1CoolingFan1               = RelayGetCoolFan1State();      // 散热风机A
    sLoadReadWriteState.u1CoolingFan2               = RelayGetCoolFan2State();      // 散热风机B
    sLoadReadWriteState.u2ConvectionFan1            = RelayGetBackFan1State();      // 对流风机+
    sLoadReadWriteState.u2ConvectionFan2            = RelayGetBackFan2State();      // 对流风机-
    
    // byte 0x03
    sLoadReadWriteState.u1RestWaterBoxDrainPump     = Hardware_GetEffluentPumpState();// 余水盒排水泵（对应板子废水泵）
    sLoadReadWriteState.u1SteamerDrainValve         = Hardware_GetEffluentValveState(); // 蒸发器排水阀（对应板子废水阀）
    sLoadReadWriteState.u1SteamerDrainPump          = Hardware_GetOutletValveState(); // 蒸发器排水泵
    sLoadReadWriteState.u1SteamerInletPump          = Hardware_GetInletValveState();  // 蒸发器进水泵
    
    // byte 0x04
    sLoadReadWriteState.u1OxygenSensor              = OxygenSensorIsWork();   // 氧传感器
    
    sLoadReadWriteState.u1DoorLock                  = OFF;                    // 门锁
    sLoadReadWriteState.u1WaxMotor                  = RelayGetMotorState();   // 蜡马达
    sLoadReadWriteState.u1OvenLamp                  = RelayGetLampState();    // 照明灯
    // byte 0x05
    sLoadReadWriteState.u7AutoDoorOpeningControl    = OFF;      // 自动开门控制
    sLoadReadWriteState.u1LockAfterAutoDoorOpening  = OFF;      // 自动开门锁定
    // byte 0x06
    sLoadReadWriteState.u8MicrowaveControl          = Inverter_GetDuty();      // 微波控制
}

/*******************************************************************************
  * 函数名：UartComm_HandleLoadControl
  * 功  能：处理负载控制
  * 参  数：无
  * 返回值：无
  * 说  明：无
*******************************************************************************/
void UartComm_HandleLoadControl(void)
{
    // 零总1继电器控制
    if((ON == sLoadReadWriteControl.u1NeutralWireMasterControl1) &&
        (OFF == RelayGetZeroLine1State()))
    {
        // 开启零总1
        RelayZeroLine1Ctrl(ON);
    }
    else if((OFF == sLoadReadWriteControl.u1NeutralWireMasterControl1) &&
        (ON == RelayGetZeroLine1State()))
    {
        // 关闭零总1
        RelayZeroLine1Ctrl(OFF);
    }

    // 零总2继电器控制
    if((ON == sLoadReadWriteControl.u1NeutralWireMasterControl2) &&
        (OFF == RelayGetZeroLine2State()))
    {
        // 开启零总2
        RelayZeroLine2Ctrl(ON);
    }
    else if((OFF == sLoadReadWriteControl.u1NeutralWireMasterControl2) &&
        (ON == RelayGetZeroLine2State()))
    {
        // 关闭零总2
        RelayZeroLine2Ctrl(OFF);
    }

    // 上外加热管处理
    if((ON  == sLoadReadWriteControl.u1TopOutsideHeater) &&
        (OFF == RelayGetUpOutHeatTubeState()))
    {
        // 开启上外加热管
        RelayCtrlUpOutHeatTube(ON);
    }
    else if((OFF == sLoadReadWriteControl.u1TopOutsideHeater) &&
        (ON == RelayGetUpOutHeatTubeState()))
    {
        // 关闭上外加热管
        RelayCtrlUpOutHeatTube(OFF);
    }

    // 上内加热管处理
    if((ON == sLoadReadWriteControl.u1TopInsideHeater) &&
        (OFF == RelayGetUpInHeatTubeState()))
    {
        // 开启上内加热管
        RelayCtrlUpInHeatTube(ON);
    }
    else if((OFF == sLoadReadWriteControl.u1TopInsideHeater) &&
        (ON == RelayGetUpInHeatTubeState()))
    {
        // 关闭上内加热管
        RelayCtrlUpInHeatTube(OFF);
    }

    // 下加热管处理
    if((ON == sLoadReadWriteControl.u1BottomHeater) &&
        (OFF == RelayGetDownHeatTubeState()))
    {
        // 开启下加热管
        RelayCtrlDownHeatTube(ON);
    }
    else if((OFF == sLoadReadWriteControl.u1BottomHeater) &&
        (ON == RelayGetDownHeatTubeState()))
    {
        // 关闭下加热管
        RelayCtrlDownHeatTube(OFF);
    }

    // 背部热管处理
    if((ON == sLoadReadWriteControl.u1BackHeater) &&
        (OFF == RelayGetBackHeatTubeState()))
    {
        // 开启背部加热管
        RelayCtrlBackHeatTube(ON);
    }
    else if((OFF == sLoadReadWriteControl.u1BackHeater) &&
        (ON == RelayGetBackHeatTubeState()))
    {
        // 关闭背部加热管
        RelayCtrlBackHeatTube(OFF);
    }

    // 蒸发盘外处理
    if(ON == sLoadReadWriteControl.u1SteamerOutsideHeater && OFF == RelayGetSteamPanOutState())
    {
        // 开启蒸发盘外管
        RelayCtrlSteamPanOut(ON);
    }
    else if(OFF == sLoadReadWriteControl.u1SteamerOutsideHeater && ON == RelayGetSteamPanOutState())
    {
        // 关闭蒸发盘外管
        RelayCtrlSteamPanOut(OFF);
    }

    // 蒸发盘内处理
    if(ON ==sLoadReadWriteControl.u1SteamerInsideHeater && OFF == RelayGetSteamPanInState())
    {
        // 开启蒸发盘内管
        RelayCtrlSteamPanIn(ON);
    }
    else if(OFF == sLoadReadWriteControl.u1SteamerInsideHeater && ON == RelayGetSteamPanInState())
    {
        // 关闭蒸发盘内管
        RelayCtrlSteamPanIn(OFF);
    }

    // 背部风扇+处理
    if((OFF != sLoadReadWriteControl.u2ConvectionFan1) &&
        (OFF == RelayGetBackFan1State()))
    {
        // 开启背部风扇+
        RelayCtrlBackFan1(ON);
    }
    else if((OFF == sLoadReadWriteControl.u2ConvectionFan1) &&
        (ON == RelayGetBackFan1State()))
    {
        // 关闭背部风扇+
        RelayCtrlBackFan1(OFF);
    }

    // 背部风扇-处理
    if((OFF != sLoadReadWriteControl.u2ConvectionFan2) &&
        (OFF == RelayGetBackFan2State()))
    {
        // 开启背部风扇-
        RelayCtrlBackFan2(ON);
    }
    else if((OFF == sLoadReadWriteControl.u2ConvectionFan2) &&
        (ON == RelayGetBackFan2State()))
    {
        // 关闭背部风扇-
        RelayCtrlBackFan2(OFF);
    }

    // 散热风扇A处理
    if((ON == sLoadReadWriteControl.u1CoolingFan1) &&
        (OFF == RelayGetCoolFan1State()))
    {
        // 开启散热风扇A
        RelayCtrlCoolFan1(ON);
    }
    else if((OFF == sLoadReadWriteControl.u1CoolingFan1) &&
        (ON == RelayGetCoolFan1State()))
    {
        // 关闭散热风扇A
        RelayCtrlCoolFan1(OFF);
    }
    
    // 散热风扇B处理
    if((ON == sLoadReadWriteControl.u1CoolingFan2) &&
            (OFF == RelayGetCoolFan2State()))
    {
        // 开启散热风扇B
        RelayCtrlCoolFan2(ON);
    }
    else if((OFF == sLoadReadWriteControl.u1CoolingFan2) &&
            (ON == RelayGetCoolFan2State()))
    {
        // 关闭散热风扇B
        RelayCtrlCoolFan2(OFF);
    }
    
    // 炉灯处理
    if((ON == sLoadReadWriteControl.u1OvenLamp) &&
            (OFF == RelayGetLampState()))
    {
        // 开启炉灯处理
        RelayCtrlLamp(ON);
    }
    else if((OFF == sLoadReadWriteControl.u1OvenLamp) &&
            (ON == RelayGetLampState()))
    {
        // 关闭炉灯处理
        RelayCtrlLamp(OFF);
    }
    
    // 蜡马达处理
    if(ON == sLoadReadWriteControl.u1WaxMotor && OFF == RelayGetMotorState())
    {
        // 开启蜡马达
        RelayCtrlMotor(ON);
    }
    else if(OFF == sLoadReadWriteControl.u1WaxMotor && ON == RelayGetMotorState())
    {
        // 关闭蜡马达
        RelayCtrlMotor(OFF);
    }

    // 预留继电器处理
    if(ON == sLoadReadWriteControl.u1ReserveRelay && OFF == RelayGetReserveState())
    {
        // 开启预留继电器
        RelayCtrlReserve(ON);
    }
    else if(OFF == sLoadReadWriteControl.u1ReserveRelay && ON == RelayGetReserveState())
    {
        // 关闭预留继电器
        RelayCtrlReserve(OFF);
    }

    // 蒸发器排水泵控制
    Hardware_OutletValveCtrl(sLoadReadWriteControl.u1SteamerDrainPump);

    // 蒸发器进水泵控制
    Hardware_InletValveCtrl(sLoadReadWriteControl.u1SteamerInletPump);
    
    // 余水盒排水泵控制
    Hardware_EffluentPumpCtrl(sLoadReadWriteControl.u1RestWaterBoxDrainPump);

    // 余水盒进水阀控制
    Hardware_EffluentValveCtrl(sLoadReadWriteControl.u1SteamerDrainValve);
    
    // 升降面板关闭控制
    if(sLoadWriteOnlyControl.u2LiftingPanelCtrl == 1
        && (Motor_GetState() == eMOTOR_OPENED 
            || Motor_GetState() == eMOTOR_OPENING_PAUSE))
    {
        // 面板只有在完全打开，或打开停止时，才能关闭
        Motor_ChangeState(eMOTOR_CLOSING);
    }

    // 升降面板打开控制
    if(sLoadWriteOnlyControl.u2LiftingPanelCtrl == 2
        && (Motor_GetState() == eMOTOR_CLOSED 
            || Motor_GetState() == eMOTOR_CLOSING_PAUSE))
    {
        // 面板只有在完全关闭，或关闭停止时，才能开启
        Motor_ChangeState(eMOTOR_OPENING);
    }

    // 升降面板停止控制
    if(sLoadWriteOnlyControl.u2LiftingPanelCtrl == 3)
    {
        if(Motor_GetState() == eMOTOR_CLOSING)
        {
            // 正在关闭，切换为关闭时停止
            Motor_ChangeState(eMOTOR_CLOSING_PAUSE);
        }
        else if(Motor_GetState() == eMOTOR_OPENING)
        {
            // 正在打开，切换为打开时停止
            Motor_ChangeState(eMOTOR_OPENING_PAUSE);
        }
    }
    
    // 氧传感器控制
    if(sLoadReadWriteControl.u1OxygenSensor == 1)
    {
        // 检测氧气传感器是否启动工作
        if(FALSE == OxygenSensorIsWork())
        {
            // 氧气传感器开始工作
            OxygenSensor_Start();
        }
    }
    else if(sLoadReadWriteControl.u1OxygenSensor == 0)
    {
        // 检测氧气传感器是否启动工作
        if(TRUE == OxygenSensorIsWork())
        {
            // 氧气传感器停止工作
            OxygenSensor_Stop();
        }
    }

    // 微波变频器控制
    Inverter_ChangeDuty(sLoadReadWriteControl.u8MicrowaveControl);
}

/*******************************************************************************
  * 函数名：UartComm_CommErrorDeviveHandler
  * 功  能：串口通讯故障-设备处理
  * 参  数：无
  * 返回值：无
  * 说  明：无
*******************************************************************************/
void UartComm_CommErrorDeviveHandler(void)
{
    // 关闭所有负载继电器
    RelayCtrlReserve(OFF);
    RelayCtrlBackFan1(OFF);
    RelayCtrlBackFan2(OFF);
    RelayCtrlMotor(OFF);
    RelayCtrlCoolFan1(OFF);
    RelayCtrlCoolFan2(OFF);
    RelayCtrlSteamPanOut(OFF);
    RelayCtrlSteamPanIn(OFF);
    RelayCtrlUpInHeatTube(OFF);
    RelayCtrlUpOutHeatTube(OFF);
    RelayCtrlDownHeatTube(OFF);
    RelayCtrlLamp(OFF);
    RelayCtrlBackHeatTube(OFF);

    // 关闭零总
    RelayZeroLine1Ctrl(OFF);
    RelayZeroLine2Ctrl(OFF);

    // 关闭泵/阀
    Hardware_OutletValveCtrl(OFF);
    Hardware_InletValveCtrl(OFF);
    Hardware_EffluentValveCtrl(OFF);
    Hardware_EffluentPumpCtrl(OFF);
}

/***************************** 文件结束 ***************************************/
